/*
 * 项目名称:cx-server
 * 类名称:KbDirectoryServiceImpl.java
 * 包名称:com.ft.oa.modules.kb.service.impl
 *
 * 修改履历:
 *     日期                       修正者        主要内容
 *     2022-01-18 11:36:00        zw     初版做成
 *
 * Copyright (c) 2019-2019 启元软件
 */
package com.ft.oa.service.knowledgeBase.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ft.oa.domain.Attachment;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.dto.knowledgeBase.KBPage;
import com.ft.oa.domain.dto.sys.SecurityUser;
import com.ft.oa.domain.knowledgeBase.Directory;
import com.ft.oa.domain.vo.knowledgeBase.DirectoryTree;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.enums.YesOrNoEnum;
import com.ft.oa.mapper.attachment.AttachmentMapper;
import com.ft.oa.mapper.knowledgeBase.DirectoryMapper;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 知识库目录表Service实现类
 * 包含知识库和附件的 内容
 *
 * @author zw
 * @date 2022-01-18 11:36:00
 */
@Service("directoryService")
public class DirectoryServiceImpl extends ServiceImpl<DirectoryMapper, Directory> implements DirectoryService
{
    @Autowired
    AttachmentMapper attachmentMapper;

    @Override
    public boolean add(Directory directory)
    {
        SecurityUser securityUser = SecurityUtils.getCurrentUser();
        directory.setCreaterUser(securityUser.getId());
        if (ObjectUtils.isEmpty(directory.getIsDel()))
        {
            directory.setIsDel(YesOrNoEnum.YES.getCode());
        }
        if (ObjectUtils.isEmpty(directory.getIsEdit()))
        {
            directory.setIsEdit(YesOrNoEnum.YES.getCode());
        }
        directory.setCreateDate(new Date());
        this.save(directory);
        if (ObjectUtils.isEmpty(directory.getParentId()))
        {
            directory.setParentId(0L);
            directory.setBelong(directory.getId());
        }
        else
        {
            Long parentId = directory.getParentId();
            while (true)
            {
                Directory directory1 = getById(parentId);
                if (directory1.getParentId().equals(0L))
                {
                    directory.setBelong(directory1.getId());
                    break;
                }
                else
                {
                    parentId = directory1.getParentId();
                }
            }
        }
        updateById(directory);
        return true;
    }

    @Override
    public boolean update(Directory directory)
    {
        if (directory.getId() != null)
        {
            Directory directory1 = this.getById(directory.getId());
            directory.setIsDel(directory1.getIsDel());
            directory.setIsEdit(directory1.getIsEdit());
            directory.setBelong(directory1.getBelong());
            if (ObjectUtils.isEmpty(directory.getParentId()))
            {
                directory.setParentId(0L);
            }
            return this.updateById(directory);
        }
        return false;
    }

    @Override
    public boolean remove(Long id)
    {
        QueryWrapper<Directory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Directory> list = baseMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0)
        {
            for (Directory directory : list)
            {
                this.removeById(directory.getId());
                remove(directory.getId());
            }
        }
        return this.removeById(id);
    }

    @Override
    public List<Directory> getDirectoryList()
    {
        QueryWrapper<Directory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        queryWrapper.orderByAsc("sort_num");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<Attachment> getAttList(KBPage kbPage)
    {
        QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("directory_id", kbPage.getDirectoryId());
        if(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager())){
            queryWrapper.eq("create_user",SecurityUtils.getCurrentUser().getId());
        }
        Page<Attachment> page = new Page<>(kbPage.getPage(), kbPage.getSize());
        IPage<Attachment> pages = attachmentMapper.selectPage(page, queryWrapper);
        return pages;
    }

    @Override
    public IPage<Attachment> getAttProList(KBPage kbPage)
    {
        IPage<Attachment> pages = null;
        if (!ObjectUtils.isEmpty(kbPage.getDirectoryId()) && !ObjectUtils.isEmpty(kbPage.getProjectNumber()))
        {
            QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("directory_id", kbPage.getDirectoryId());
            queryWrapper.eq("project_number", kbPage.getProjectNumber());
            if(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager())){
                queryWrapper.eq("create_user",SecurityUtils.getCurrentUser().getId());
            }
            Page<Attachment> page = new Page<>(kbPage.getPage(), kbPage.getSize());
            pages = attachmentMapper.selectPage(page, queryWrapper);
        }
        return pages;
    }

    @Override
    public List<DirectoryTree> getDirectoryTree(Long id)
    {
        QueryWrapper<Directory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("belong", id);
        List<Directory> list = baseMapper.selectList(queryWrapper);
        return handleDirectoryTree(list, 0L);
    }

    public List<DirectoryTree> handleDirectoryTree(List<Directory> list, Long id)
    {
        List<DirectoryTree> drList = new ArrayList<>();
        if (list != null && list.size() > 0)
        {
            int i = 0;
            for (Directory directory : list)
            {
                if (id.equals(directory.getParentId()))
                {
                    DirectoryTree directoryTree = new DirectoryTree();
                    directoryTree.setId(directory.getId());
                    directoryTree.setLabel(directory.getDirectoryName());
                    directoryTree.setIsDel(directory.getIsDel());
                    directoryTree.setIsEdit(directory.getIsEdit());
                    directoryTree.setRemark(directory.getRemark());
                    List<DirectoryTree> directoryTrees = handleDirectoryTree(list, directory.getId());
                    directoryTree.setChildren(directoryTrees);
                    drList.add(directoryTree);
                    i++;
                }
            }
            if (i == 0)
            {
                drList = null;
            }
        }
        return drList;
    }

    @Override
    public void saveProAttachment(List<AttachmentDto> attachments, String source, String relationId, String sourceId, String[] projectNumbers)
    {
        if (projectNumbers != null && projectNumbers.length > 0)
        {
            for (String projectNumber : projectNumbers)
            {
                saveProAttachment(attachments, source, relationId, sourceId, projectNumber);
            }
        }
    }

    /**
     * @param attachments
     * @param source
     * @param relationId
     * @param sourceId
     */
    @Override
    public void saveProAttachment(List<AttachmentDto> attachments, String source, String relationId, String sourceId, String projectNumber)
    {
        SecurityUser user = SecurityUtils.getCurrentUser();
        if (attachments != null && attachments.size() > 0)
        {
            removeAttachment(source, relationId);
            QueryWrapper<Directory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", source);
            Directory queryDirectory = baseMapper.selectOne(queryWrapper);
            for (AttachmentDto attachmentDto : attachments)
            {
                Attachment attachment = new Attachment();
                attachment.setPath(attachmentDto.getPath());
                attachment.setName(attachmentDto.getName());
                attachment.setFilesize(attachmentDto.getFilesize());
                String fileName = attachmentDto.getPath().substring(attachmentDto.getPath().lastIndexOf("/") + 1);
                attachment.setFileName(fileName);
                String type = attachmentDto.getPath().substring(attachmentDto.getPath().lastIndexOf(".") + 1);
                attachment.setType(type);
                attachment.setRelationId(relationId);
                attachment.setSource(DirectoryTypeEnum.getByCode(source));
                attachment.setSourceId(sourceId);
                attachment.setCreateUser(user.getId());
                attachment.setProjectNumber(projectNumber);
                attachment.setDirectiryId(queryDirectory.getId());
                attachmentMapper.insert(attachment);
            }
        }
    }

    public void removeAttachment(String source, String relationId)
    {
        if (!ObjectUtils.isEmpty(source) && !ObjectUtils.isEmpty(relationId))
        {
            QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("source", source);
            queryWrapper.eq("relation_id", relationId);
            List<Attachment> list = attachmentMapper.selectList(queryWrapper);
            if (list != null && list.size() > 0)
            {
                for (Attachment attachment : list)
                {
                    attachmentMapper.deleteById(attachment.getId());
                }
            }
        }
    }

    @Override
    public void saveAttachment(List<AttachmentDto> attachments, String source, String relationId, String sourceId, String dir)
    {
        if (attachments != null && attachments.size() > 0)
        {
            Long directiryId = null;
            SecurityUser securityUser = SecurityUtils.getCurrentUser();
            QueryWrapper<Directory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", source);
            Directory queryDirectory = baseMapper.selectOne(queryWrapper);
            directiryId = queryDirectory.getId();
            if (!ObjectUtils.isEmpty(dir)
            )
            {
                Directory directory = new Directory();
                directory.setCreaterUser(securityUser.getId());
                directory.setIsDel(YesOrNoEnum.YES.getCode());
                directory.setIsEdit(YesOrNoEnum.YES.getCode());
                directory.setCreateDate(new Date());
                directory.setParentId(queryDirectory.getId());
                directory.setBelong(queryDirectory.getBelong());
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("parent_id", directory.getId());
                queryWrapper.orderByAsc("sort_num");
                List<Directory> list = baseMapper.selectList(queryWrapper);
                if (list != null && list.size() > 0)
                {
                    Directory directory1 = list.get(list.size() - 1);
                    Long sortNum = directory1.getSortNum() + 1;
                    directory.setSortNum(sortNum);
                }
                else
                {
                    directory.setSortNum(1L);
                }
                this.save(directory);
                directiryId = directory.getId();
            }
            removeAttachment(source, relationId);
            for (AttachmentDto attachmentDto : attachments)
            {
                Attachment attachment = new Attachment();
                attachment.setPath(attachmentDto.getPath());
                attachment.setName(attachmentDto.getName());
                attachment.setFilesize(attachmentDto.getFilesize());
                String fileName = attachmentDto.getPath().substring(attachmentDto.getPath().lastIndexOf("/") + 1);
                attachment.setFileName(fileName);
                String type = attachmentDto.getPath().substring(attachmentDto.getPath().lastIndexOf(".") + 1);
                attachment.setType(type);
                attachment.setRelationId(relationId);
                attachment.setSource(DirectoryTypeEnum.getByCode(source));
                attachment.setSourceId(sourceId);
                attachment.setCreateUser(securityUser.getId());
                attachment.setDirectiryId(directiryId);
                attachmentMapper.insert(attachment);
            }
        }
    }

    @Override
    public void saveAttachment(AttachmentDto attachmentDto)
    {
        Attachment attachment = new Attachment();
        attachment.setPath(attachmentDto.getPath());
        attachment.setName(attachmentDto.getName());
        attachment.setFilesize(attachmentDto.getFilesize());
        String fileName = attachmentDto.getPath().substring(attachmentDto.getPath().lastIndexOf("/") + 1);
        attachment.setFileName(fileName);
        String type = attachmentDto.getPath().substring(attachmentDto.getPath().lastIndexOf(".") + 1);
        attachment.setType(type);
        attachmentMapper.insert(attachment);
    }

}
